package idv.arthur.work;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class KeepCommentMR
 */
//@WebServlet(description = "將對MR的意見寫入DB", urlPatterns = { "/KeepCommentMR" })
public class KeepCommentMR extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public KeepCommentMR() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/** 將此測試項目的 
		 * 	1. isTRSubmitted 改為 1
		 * 	2. isTRReviewed 改為0
		 * **/
		request.setCharacterEncoding("UTF-8");
		Widgets wid = new Widgets();
		Connection conn = null;
		PreparedStatement ps = null;
		String returnResult = "OK";
		String strSQL = "SELECT MAX(ver) FROM tms_mrtcmapping WHERE tpid=? AND mrid=?";
		int tpid = Integer.parseInt(request.getParameter("tpid"));
		String mrid = request.getParameter("mrid");
		String comment = request.getParameter("submitorComment").trim();
		int ver = 0;
		String creator = request.getParameter("loginUser");					//提交人員的ID
		String submittedBy = request.getParameter("submittedBy");			//提交人員的角色
		ResultSet rs = null;
		
		try {
			/** 將測試項目的狀態改為已送審，但尚未審 **/
			conn = wid.getConn(true);
			ps = conn.prepareStatement(strSQL);
			ps.setInt(1, tpid);
			ps.setString(2, mrid);
			rs = ps.executeQuery();
			rs.next();
			ver = rs.getInt(1);
			
			wid.keepCommentMR(tpid, mrid, ver, comment, 2, creator, submittedBy, conn, ps);
		} catch (SQLException e) {
			returnResult = wid.keepErrorMes(conn, ps, e,"", true);
		} finally {
			try {
				if (rs != null) {rs.close();}
				if (ps != null) {ps.close();}
				if (conn != null) {conn.close();}
			} catch (SQLException e) {
				returnResult = e.toString();
			}
		}
		
		response.setContentType("application/text");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(returnResult);
	}

}
